/*
 * Developer : Jack Matthews
 * Email: developer@droidprofessor.com
 * 
 * Copyright (C) 2010 http://droidprofessor.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.droidprofessor.android.library.phonelicenses;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import com.android.vending.licensing.LicenseChecker;
import com.android.vending.licensing.LicenseCheckerCallback;
import com.android.vending.licensing.StrictPolicy;
import com.droidprofessor.android.licensegenerator.client.AndroidClientLicenseImpl;


public class ActivityAndroidMarketLicenseCheck extends Activity {
	private static final String TAG = "ActivityAndroidMarketLicenseCheck";
	private LicenseChecker mChecker;
	private LicenseCheckerCallback mLicenseCheckerCallback;
	//private ProgressDialog progressDialog;
	private Handler handler = new Handler();
	

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			//Public Key
			String publicKey = (ApplicationDataCache.getInstance().getPaymentMethodByReferenceName(ApplicationDataCache.PaymentMethod.REFNAME_ANDROIDMARKET_INTEGRATED)).getExtra("androidmarketPublicKey");
			// Library calls this when it's done.
			mLicenseCheckerCallback = new LicenseCheckerCallbackImpl();
			// Construct the LicenseChecker with a policy.
			mChecker = new LicenseChecker(this, new StrictPolicy(), publicKey);
			//Show the progress
			showContactingServerDialog("Android Market");
			//Check the licenses
			doCheck();
		} catch (Exception e) {
			Log.e(TAG, "Exception", e);
			Toast.makeText(this, "Unable to initialise payment, check you public key in PhoneLicenses parameters", Toast.LENGTH_LONG).show();
			setResult(PhoneLicensesCodes.RESULT_CODE_ERROR);
			finish();
		}
	}
	
	



	/**
	 * Perform an actual check of the license
	 */
	private void doCheck() {
		mChecker.checkAccess(mLicenseCheckerCallback);
	}
	
	
	
	

//	@Override
//	protected Dialog onCreateDialog(int id) {
//		// We have only one dialog.
//		return new AlertDialog.Builder(this)
//				.setTitle("Application Not Licensed")
//				.setCancelable(false)
//				.setMessage(
//						"This application is not licensed. Please purchase it from Android Market")
//				.setPositiveButton("Buy App",
//						new DialogInterface.OnClickListener() {
//							@Override
//							public void onClick(DialogInterface dialog,
//									int which) {
//								Intent marketIntent = new Intent(
//										Intent.ACTION_VIEW,
//										Uri.parse("http://market.android.com/details?id="
//												+ getPackageName()));
//								startActivity(marketIntent);
//								finish();
//							}
//						})
//				.setNegativeButton("Exit",
//						new DialogInterface.OnClickListener() {
//							@Override
//							public void onClick(DialogInterface dialog,
//									int which) {
//								finish();
//							}
//						}).create();
//	}


	private String dialogMessage = "";
	private void showContactingServerDialog(String serverName) {
		String message = String.format(
				getString(R.string.com_phonelicenses_contacting_x), 
				serverName);
		dialogMessage = message;
		showDialog(PhoneLicensesCodes.DIALOG_PROGRESS);
	}
	
	
	
	
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		
		switch (id) {
		case PhoneLicensesCodes.DIALOG_PROGRESS:
			dialog = new ProgressDialog(this);
			((ProgressDialog)dialog).setMessage("");
			((ProgressDialog)dialog).setProgressStyle(ProgressDialog.STYLE_SPINNER);
			((ProgressDialog)dialog).setCancelable(false);
			((ProgressDialog)dialog).setIndeterminate(false);
			break;

		default:
			break;
		}
		
		return dialog;
	}


	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case PhoneLicensesCodes.DIALOG_PROGRESS:
			((ProgressDialog)dialog).setMessage(dialogMessage);
			break;

		default:
			break;
		}
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
		mChecker.onDestroy();
	}


//	public void toast(String string) {
//		Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
//	}

	
	/**
	 * A PhoneLicenses Implementation of the LicenseChecker.
	 * 
	 * An attempt is made to create a new account on the server for the user
	 * 
	 * 
	 * @author Jack Matthews
	 *
	 */
	private class LicenseCheckerCallbackImpl implements LicenseCheckerCallback, HttpResponseListener {

		private String userId;


		@Override
		public void allow(int responseCode, String signedData, String signature, int nonce, String packageName, String versionCode, String userId) {
			if (isFinishing()) {
				// Don't update UI if Activity is finishing.
				return;
			}
			
			this.userId = userId; //for setting the transaction number
			
			//Change the dialog
			handler.post(new Runnable() {
				
				@Override
				public void run() {
					dismissDialog(PhoneLicensesCodes.DIALOG_PROGRESS);
					showContactingServerDialog(ApplicationDataCache.getInstance().getMerchantName());
				}
			});
			
			
			
			//Now we know the data is valid we can send a request to the server
			List<NameValuePair> get = new ArrayList<NameValuePair>();
			get.add(new BasicNameValuePair("option", "com_phonelicenses" ));    
			get.add(new BasicNameValuePair("view", "ipn" ));    
			get.add(new BasicNameValuePair("controller", "androidmarket" ));    
			get.add(new BasicNameValuePair("format", "xml" )); 	
			get.add(new BasicNameValuePair("auth_key", AndroidClientLicenseImpl.getInstance().getAuthKey() )); 
//			get.add(new BasicNameValuePair("application_id", AndroidClientLicenseImpl.getInstance().getApplicationId() ));
	
			List<NameValuePair> post = new ArrayList<NameValuePair>();
			post.add(new BasicNameValuePair("responseCode", String.valueOf(responseCode) )); 
			post.add(new BasicNameValuePair("signedData", signedData )); 
			post.add(new BasicNameValuePair("signature", signature ));
			post.add(new BasicNameValuePair("nonce", String.valueOf(nonce) ));
			post.add(new BasicNameValuePair("username", PreferencesHelper.getUsername(ActivityAndroidMarketLicenseCheck.this) )); 
			post.add(new BasicNameValuePair("email", PreferencesHelper.getEmail(ActivityAndroidMarketLicenseCheck.this) )); 
			post.add(new BasicNameValuePair("packageName", packageName )); 
			post.add(new BasicNameValuePair("versionCode", versionCode )); 

	
			HttpUrlRequest.sendRequest(
					AndroidClientLicenseImpl.getInstance().getScheme(),
					AndroidClientLicenseImpl.getInstance().getHost(),
					AndroidClientLicenseImpl.getInstance().getPort(), 
					AndroidClientLicenseImpl.getInstance().getPath(),
					get, 
					post,
					PhoneLicensesCodes.REQUEST_CODE_GET_ANDROIDMARKET_LICENSE,
					this
			);
		}
	
	
		@Override
		public void applicationError(ApplicationErrorCode errorCode) {
			if (isFinishing()) {
				// Don't update UI if Activity is finishing.
				return;
			}
			// This is a polite way of saying the developer made a mistake
			// while setting up or calling the license checker library.
			// Please examine the error code and fix the error.
			setResult(
					PhoneLicensesCodes.RESULT_CODE_ERROR, 
					(new Intent()).putExtra("message",errorCode.name()) 
					);
			finish();
		}
	
		@Override
		public void dontAllow() {
			if (isFinishing()) {
				// Don't update UI if Activity is finishing.
				return;
			}
	
			// Should not allow access. In most cases, the app should assume
			// the user has access unless it encounters this. If it does,
			// the app should inform the user of their unlicensed ways
			// and then either shut down the app or limit the user to a
			// restricted set of features.
			// In this example, we show a dialog that takes the user to Market.
			//showDialog(0);
			setResult(
					PhoneLicensesCodes.RESULT_CODE_DONT_ALLOW, 
					(new Intent()).putExtra("message", "Error: You have not yet paid for the application")
					);
			finish();
		}
		
		
		@Override
		public void onResponseReceived(HttpResponse response, int requestCode) {
				//Common code required by all HTTP responses
				if(response==null) {
					setResult(
							PhoneLicensesCodes.RESULT_CODE_ERROR, 
							(new Intent()).putExtra("message",getString(R.string.com_phonelicenses_communication_error)) 
							);
					finish();
					return;
				}
				
				HttpEntity entity = response.getEntity();
				BufferedInputStream bis;
				
				try {
					if(entity != null) {
						InputStream in = entity.getContent();
						bis = new BufferedInputStream(in);
						Utils.logInpuStream(bis);
					}
					else {
						setResult(
								PhoneLicensesCodes.RESULT_CODE_ERROR, 
								(new Intent()).putExtra("message", "The Server returned an empty response")
								);
						finish();
						return;
					}
				} catch (IllegalStateException e) {
					Log.e(TAG, "IllegalStateException", e);
					setResult(
							PhoneLicensesCodes.RESULT_CODE_ERROR, 
							(new Intent()).putExtra("message", "IllegalStateException")
							);
					finish();
					return;
				} catch (IOException e) {
					Log.e(TAG, "IOException", e);
					setResult(
							PhoneLicensesCodes.RESULT_CODE_ERROR, 
							(new Intent()).putExtra("message", "IOException")
							);
					finish();
					return;
				} finally {
					//hide the progress bar
					dismissDialog(PhoneLicensesCodes.DIALOG_PROGRESS);
					setProgressBarIndeterminateVisibility(false);
				}
				
				
				
				
				switch (requestCode) {
				case PhoneLicensesCodes.REQUEST_CODE_GET_ANDROIDMARKET_LICENSE:			
					XmlResponse<String> xmlResponse = XmlParser.parseXmlLicense(bis);

					if(xmlResponse.isError()) {
						Log.e(TAG, xmlResponse.toString() );
						setResult(
								PhoneLicensesCodes.RESULT_CODE_ERROR, 
								(new Intent()).putExtra("message", xmlResponse.getMessage())
								);
						finish();
					} else { //ALL WAS OK
						Log.d(TAG, xmlResponse.getMessage());
						PreferencesHelper.setTransactionNo(ActivityAndroidMarketLicenseCheck.this, this.userId);
						//setResult(PhoneLicensesCodes.RESULT_CODE_REGISTERED);
						setResult(
								PhoneLicensesCodes.RESULT_CODE_LICENSE_CREATED, 
								(new Intent()).putExtra("message", String.format("A new License has been created for %s, a license is now being downloaded and installed on your phone", PreferencesHelper.getUsername(ActivityAndroidMarketLicenseCheck.this)))
								);
						finish();
					}
					
					return;
				default:
					break;
				}
				
				//In case of an error
				Log.e(TAG, "Should never have gotten here" );
				setResult(
						PhoneLicensesCodes.RESULT_CODE_ERROR, 
						(new Intent()).putExtra("message", String.format("We received a request code (%s) that was not handled by the system", requestCode)) 
						);
				finish();
		}
	
	
	}

}
